package com.jiangjiang.eshop.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.jiangjiang.eshop.auth.dao.PriorityMapper;
import com.jiangjiang.eshop.auth.domain.PriorityEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName PriorityService
 * @Description TODO
 * @Author jhw
 * @Date 2021/4/20 21:30
 * @Version 1.0
 **/
@Service
public class PriorityService extends ServiceImpl<PriorityMapper, PriorityEntity> {

    @Autowired
    private PriorityMapper priorityMapper;

    /**
     * 查询所有根权限
     */
    public List<PriorityEntity> listRootPriorities() {
        LambdaQueryWrapper<PriorityEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.isNull(PriorityEntity::getParentId);
        return this.getBaseMapper().selectList(wrapper);
    }

    /**
     * 根据父权限id查询子权限
     */
    public List<PriorityEntity> listChildrenPriorities(Long parentId) {
        LambdaQueryWrapper<PriorityEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PriorityEntity::getParentId, parentId);
        return this.getBaseMapper().selectList(wrapper);
    }

    /**
     * 根据id查询权限
     */
    public PriorityEntity queryById(Long id) {
        LambdaQueryWrapper<PriorityEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PriorityEntity::getId, id);
        return this.getOne(wrapper);
    }

    /**
     * 删除权限节点
     *
     * @param id 权限节点id
     */
    public void removePriority(Long id) {
        this.removeById(id);
    }

    /**
     * @param accountId
     * @return
     */
    public List<PriorityEntity> listAuthorizedTreeByAccountId(Long accountId, Long parentId) {
        Map<String, Object> conditions = Maps.newHashMap();
        conditions.put("accountId", accountId);
        conditions.put("parentId", parentId);
        return priorityMapper.listAuthorizedTreeByAccountCondition(conditions);
    }

    /**
     * 统计账号对指定url的权限是否有授权记录
     *
     * @param accountId 账号id
     * @param url       权限url
     * @return 是否有授权记录
     */
    public Long countAuthorizedByUrl(Long accountId, String url) {
        return priorityMapper.countAuthorizedByUrl(accountId, url);
    }


    /**
     * 统计账号对指定编号的权限是否有授权记录
     *
     * @param accountId 账号id
     * @param code      权限u编号
     * @return 是否有授权记录
     */
    public Long existAuthorizedByCode(Long accountId, String code) {
        return priorityMapper.existAuthorizedByCode(accountId, code);
    }

    /**
     * 根据权限id查询与之绑定的账号id
     *
     * @param id 权限id
     * @return 查询结果
     */
    public List<Long> listAccountIdsByPriorityId(Long id) {
        return priorityMapper.listAccountIdsByPriorityId(id);
    }
}
